//
//  Status.swift
//  WeiBo
//
//  Created by 刘星 on 16/6/19.
//  Copyright © 2016年 LiuXing. All rights reserved.
//

import UIKit
import SDWebImage

class Status: NSObject {
    /// 微博创建时间
    var created_at: String?
    /// 微博Id
    var id: Int = 1
    /// 微博内容
    var text: String?
    /// 微博来源
    var source: String?
    /// 配图数组
    var pic_urls: [[String: AnyObject]]? {
        didSet {
            // 1.初始化数组
            storedPicURLS = [NSURL]()
            // 2遍历取出所有的图片路径字符串
            for dict in pic_urls!
            {
                if let urlStr = dict["thumbnail_pic"]
                {
                    // 将字符串转换为URL保存到数组中
                    storedPicURLS?.append(NSURL(string: urlStr as! String)!)
                }
            }
        }
    }
    /// 用户信息
    var user: User?
    /// 保存当前微博所有配图的URL
    var storedPicURLS: [NSURL]?
    /// 字典转模型
    init(dict: [String: AnyObject]) {
        super.init()
        setValuesForKeysWithDictionary(dict)
    }
    override func setValue(value: AnyObject?, forKey key: String) {
        if "user" == key {
            user = User.init(dict: value as![String : AnyObject])
            return
        }
        super.setValue(value, forKey: key)
    }
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
    }
    class func dict2Model(list: [[String: AnyObject]]) -> [Status] {
        var models = [Status]()
        for dict in list {
            models.append(Status.init(dict: dict))
        }
        return models
    }
    // 打印模型
    let properites = ["created_at", "id", "text", "source", "pic_urls"]
    override var description: String {
        let dict = dictionaryWithValuesForKeys(properites)
        return "\(dict)"
    }
    /// 加载微博数据
    class func loadStatuses(finished: (models: [Status]?, error: NSError?)->()) {
        let path = "2/statuses/home_timeline.json"
        let params = ["access_token": UserAccount.loadAccount()!.access_token!]
        NetworkTools.shareNetworkTools().GET(path, parameters: params, progress: { (progress) in
            print(progress)
            }, success: { (task, JSON) in
                // 取出statuses对应的数据，里面是字典
                let models = dict2Model(JSON!["statuses"] as! [[String: AnyObject]])
                cacheStatusImages(models, finished: finished)
//                finished(models: models, error: nil)
                // 转成模型
            }) { (_, error) in
                print(error)
                finished(models: nil, error: error)
        }
    }
    class func cacheStatusImages(list: [Status], finished: (models:[Status]?, error:NSError?)->()) {
        
        // 1.创建一个组
        let group = dispatch_group_create()
        
        // 1.缓存图片
        for status in list
        {
//            if status.storedPicURLS == nil {
//                continue
//            }
            guard let url = status.storedPicURLS else {
                continue
            }
            for url in status.storedPicURLS!
            {
                // 将当前的下载操作添加到组中
                dispatch_group_enter(group)
                
                // 缓存图片
                SDWebImageManager.sharedManager().downloadImageWithURL(url, options: SDWebImageOptions(rawValue: 0), progress: nil, completed: { (_, _, _, _, _) -> Void in
                    
                    // 离开当前组
                    dispatch_group_leave(group)
                    //                    print("OK")
                })
            }
        }
        
        // 2.当所有图片都下载完毕再通过闭包通知调用者
        dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
            print("Over")
            // 能够来到这个地方, 一定是所有图片都下载完毕
            finished(models: list, error: nil)
        }
    }
}
